package org.exhaust.barbecue.action;

import org.exhaust.barbecue.AbstractRequest;
import org.exhaust.barbecue.ActionContext;
import org.exhaust.barbecue.model.BasePagedRequest;
import org.hibernate.validator.HibernateValidator;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

public class ParamsAutoValidateAction extends AbstractValidatorAction {

    private Validator validator;

    public ParamsAutoValidateAction() {
        this.validator = Validation.byProvider(HibernateValidator.class)
                .configure()
                .failFast(true) //有一个失败就停止检查
                .buildValidatorFactory()
                .getValidator();
    }

//    public final static ParamsAutoValidateAction INSTANCE = new ParamsAutoValidateAction();

    @Override
    protected void validate(AbstractRequest request, ActionContext context) {
        if (request instanceof BasePagedRequest) {
            BasePagedRequest basePagedRequest = (BasePagedRequest) request;
            if (basePagedRequest.getPageNo() <= 0) {
                throw new RuntimeException("页码必须大于0");
            }
            if (basePagedRequest.getPageSize() <= 0) {
                throw new RuntimeException("每页条数必须大于0");
            }
        }

        Set<ConstraintViolation<AbstractRequest>> constraintViolationSet = validator.validate(request);
        for (ConstraintViolation constraintViolation : constraintViolationSet) {
            throw new RuntimeException(constraintViolation.getMessage());
        }
    }
}
